
/**
 *https://leetcode.cn/problems/median-of-two-sorted-arrays/?favorite=2cktkvj
 * 查找中位数
 * 方法：
 * 1.循环然后合并，O(m+n)
 * 2.双指针,o(m+n)
 * 3.第k小的数
 * 4.2分查找，O(log(m+n))
 * 解题思路：
 * 1.把数组先合并
 * 2.寻找数组中位数
 * 
 *  @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
 var findMedianSortedArrays = function(nums1, nums2) {
    
    let mergedArr=[];
    let max=nums1.length+nums2.length;
    let midIndex=max%2===0?max/2:Math.floor(max/2)
    let i=0,j=0,counter=0;
    while(i+j<max){

        if((nums1[i]!=undefined && nums1[i]<=nums2[j]) || nums2[j]== undefined){
            mergedArr.push(nums1[i])
            i++;
        }else{
            mergedArr.push(nums2[j]);
            j++;
        }

        // console.log(counter,midIndex)
        if(counter==midIndex){
            if(max%2===0){
                return (mergedArr[midIndex-1]+mergedArr[midIndex])/2
            }else{
                return mergedArr[midIndex]
            }
            
        }
        
        counter++;
        
        
    }
    // console.log(mergedArr)
    //return findMedian(mergedArr); 
};

var findMedianSortedArrays2 = function(nums1, nums2) {
    
    let mergedArr=[];
    let max=nums1.length+nums2.length;
    let i=0,j=0;
    while(i+j<max){

        if((nums1[i]!=undefined && nums1[i]<=nums2[j]) || nums2[j]== undefined){
            mergedArr.push(nums1[i])
            i++;
        }else{
            mergedArr.push(nums2[j]);
            j++;
        }
        
    }
    console.log(mergedArr)
    return findMedian(mergedArr); 
};

console.log(findMedianSortedArrays([1,2],[3,4]))
function findMedian(arr){
    let midIndex=0;
    if(arr.length%2===0){
        midIndex=arr.length/2;
        return (arr[midIndex-1]+arr[midIndex])/2
    }else{
        midIndex=Math.floor(arr.length/2);
        return arr[midIndex]
    }  
}


// const arr = [];
// const median = findMedian(arr); // 4
// console.log(median)
